package com.caifu.controller;


import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.FileOutputStream;

/**
 * ClassName :ImgController
 *
 * @author :
 * @description ：
 * @date : 2021-03-01 11:26
 */
@Controller
@RequestMapping(value = "/img")
public class ImageController {


    @Value("${file.upload.path}")
    private String imageUrlPath;

    @Value("${file.upload.result.path}")
    private String imgSocialPath;


    /**
     *
     * @param uploadFile uploadFile
     * @return String
     */
    @RequestMapping("/pic/uploadImage")
    @ResponseBody
    public String ajaxUploadImage(@RequestParam(value = "file", required = false) MultipartFile uploadFile) {
        JSONObject result = new JSONObject();
        try {
            String fileName = System.currentTimeMillis()+ ".jpg";
            //测试用
            String filePath = imgSocialPath + "/WLstoreArchivesManageSystem";
            String imgPath = imageUrlPath + "/WLstoreArchivesManageSystem";
            uploadFile(uploadFile.getBytes(), imgPath, fileName);
            result.put("code", "0000");
            result.put("msg", filePath+"/"+fileName);
            return result.toString();
        } catch (Exception e) {
            e.printStackTrace();
            result.put("code", "9999");
            result.put("msg", "图片上传失败");
            return result.toString();
        }
    }


    public static void uploadFile(byte[] file, String filePath, String fileName) {
       try{
           File targetFile = new File(filePath);
           if (!targetFile.exists()) {
               boolean b = targetFile.mkdirs();
           }
           FileOutputStream out = new FileOutputStream(filePath + "/" + fileName);
           out.write(file);
           out.flush();
           out.close();
       } catch(Exception e){
           e.printStackTrace();
       }
    }


}
